package com.zzzzzz.app.topic.controller;

import java.util.Date;
import java.util.Locale;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.zzzzzz.app.account.model.po.User;
import com.zzzzzz.app.account.service.UserManager;
import com.zzzzzz.app.topic.NoSuchTopicException;
import com.zzzzzz.app.topic.model.bo.TopicBo;
import com.zzzzzz.app.topic.model.po.Topic;
import com.zzzzzz.app.topic.model.vo.TopicVo;
import com.zzzzzz.app.topic.service.TopicManager;
import com.zzzzzz.common.util.Validator;
import com.zzzzzz.core.controller.BaseController;

@Controller
public class TopicController extends BaseController {

	@Resource
	private UserManager userManager;
	
	@Resource
	private TopicManager topicManager;

	@Resource
	private MessageSource messageSource;
	
	/** binder用于bean属性的设置 */
	/**
	@InitBinder
	public void initBinder(WebDataBinder binder) {
	        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));  
	}
	*/

	@RequiresUser
	@RequestMapping(value = "/topic/add", method = RequestMethod.GET)
	public String viewAddPage(Model model, @ModelAttribute TopicVo topicVo) {
		model.addAttribute("cur", "new_topic");
		return "topic/add_or_edit";
	}

	@RequiresUser
	@RequestMapping(value = "/topic/edit/{id}", method = RequestMethod.GET)
	public String viewEditPage(Model model, @ModelAttribute TopicVo topicVo, @PathVariable Long id) throws Exception {
		try{
			model.addAttribute("cmd", "edit");
			Topic topic = topicManager.findById(id);
			topicVo.setTopicId(topic.getTopicId());
			topicVo.setTitle(topic.getTitle());
			topicVo.setContent(topic.getContent());
		} catch (Exception e) {
			if(e instanceof NoSuchTopicException) {
				model.addAttribute("msg_error_topic_not_found", messageSource.getMessage("message.error.topic.not.found", new Object[]{}, Locale.ROOT));
				logger.error(e.getMessage());
			}else {
	    		logger.error(e.getMessage(), e);
	    		throw e; // handle by Spring
			}
		}
		return "topic/add_or_edit";
	}

	@RequiresUser
	@RequestMapping(value = "/topic/add_or_edit", method = RequestMethod.POST)
	public String processAddOrEdit(Model model, @ModelAttribute TopicVo topicVo, BindingResult result) throws Exception {
		if(result.hasErrors()) {
			result.reject("message.error.process.request");
			if(Validator.isNull(topicVo.getTopicId())) {
				return viewAddPage(model, topicVo);
			}else {
				return viewEditPage(model, topicVo, topicVo.getTopicId());
			}
		}

		try{
			Topic topic = null;
			if(Validator.isNull(topicVo.getTopicId())) {
				// add topic
				topic = new Topic();
				topicVo.updatePo(topic);
				Date now = new Date();
				topic.setCreateDate(now);
				topic.setModifiedDate(now);
				Long userId = userManager.findCurrentUserId();
				topic.setUserId(userId);
				topicManager.add(topic);
			}else {
				// edit topic
				topic = topicManager.findById(topicVo.getTopicId());
				topicVo.updatePo(topic);
				Date now = new Date();
				topic.setModifiedDate(now);
				topicManager.edit(topic);
				
			}
			return "redirect:/topic/" + topic.getTopicId();
		} catch (Exception e) {
    		logger.error(e.getMessage(), e);
    		throw e; // handle by Spring
		}
	}
	
	@RequestMapping(value = "/topic/{id}", method = RequestMethod.GET)
	public String viewDetailPage(Model model, @PathVariable Long id, HttpServletRequest request) throws Exception {
		TopicBo topicBo = null;
		try{
			Topic topic = topicManager.findById(id);
			User user = userManager.findById(topic.getUserId());
			topicBo = new TopicBo(topic, user);
			model.addAttribute("topicBo",topicBo);
			request.setAttribute("topicId", id);
		} catch (Exception e) {
			if(e instanceof NoSuchTopicException) {
				model.addAttribute("msg_topic_not_found", messageSource.getMessage("message.error.topic.not.found", new Object[]{}, Locale.ROOT));
				logger.error(e.getMessage());
			}else {
	    		logger.error(e.getMessage(), e);
	    		throw e; // handle by Spring
			}
		}
		return "topic/view";
	}
	
	private static Logger logger = Logger.getLogger(TopicController.class);
	
}